﻿// *********************************************************************
// * Copyright © 2013 Thomas Due
// *
// * This file is the property of Thomas Due and may not be 
// * distributed without the written consent of the author.    
// ********************************************************************

using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using SqlPad.Library.Interfaces;
using SqlPad.Library.Models;

namespace SqlPad.Library.QueryHandlers
{
    public class SimpleQueryHandler : IQueryHandler<DataTable>
    {
        private IQueryResult<DataTable> _result;

        public string ConnectionString { get; set; }

        public IQueryResult<DataTable> Run(string connectionString, string query)
        {
            ConnectionString = connectionString;
            return Run(query);
        }

        public IQueryResult<DataTable> Run(string query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            if (string.IsNullOrEmpty(ConnectionString))
            {
                throw new NullReferenceException("ConnectionString is not set.");
            }

            var timer = Stopwatch.StartNew();
            try
            {
                DataTable schema;
                var dataTable = new DataTable("ResultTable");

                using (var sql = new SqlConnection(ConnectionString))
                {
                    sql.Open();
                    using (var cmd = sql.CreateCommand())
                    {
                        cmd.CommandText = query;

                        //This will get a lot of info about query fields
                        using (var reader = cmd.ExecuteReader(CommandBehavior.KeyInfo))
                        {
                            schema = reader.GetSchemaTable();
                        }

                        using (var sqlAdapter = new SqlDataAdapter(cmd))
                        {
                            sqlAdapter.Fill(dataTable);
                        }

                    }
                }
                timer.Stop();

                _result = new DataTableQueryResult(query, timer.Elapsed, dataTable, schema);
            }
            catch (Exception)
            {
                timer.Stop();
                throw;
            }
            return _result;
        }

        public IQueryResult<DataTable> Result()
        {
            return _result;
        }
    }
}